import React, { useState } from 'react';
import { IonContent } from '@ionic/react';
import { useOllama } from '../hooks/useOllama';

export const ModelManager: React.FC = () => {
  const { 
    models, 
    isServerRunning, 
    isLoading, 
    error,
    startServer,
    stopServer,
    createModel,
    deleteModel,
    refreshModels
  } = useOllama();

  const [modelName, setModelName] = useState('');
  const [modelFile, setModelFile] = useState('');

  const handleCreateModel = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!modelName || !modelFile) return;

    try {
      await createModel(modelName, modelFile);
      setModelName('');
      setModelFile('');
    } catch (err) {
      console.error('Failed to create model:', err);
    }
  };

  return (
    <IonContent className="ion-padding">
      <div className="card w-full bg-base-100 shadow-xl">
        <div className="card-body">
          <h2 className="card-title text-primary">Ollama Model Manager</h2>

          {/* Server Status */}
          <div className="flex items-center gap-4 mb-4">
            <div className="flex items-center gap-2">
              <div className={`badge ${isServerRunning ? 'badge-success' : 'badge-error'}`}>
                Server {isServerRunning ? 'Running' : 'Stopped'}
              </div>
            </div>
            <button 
              className={`btn btn-sm ${isServerRunning ? 'btn-error' : 'btn-success'}`}
              onClick={() => isServerRunning ? stopServer() : startServer()}
              disabled={isLoading}
            >
              {isServerRunning ? 'Stop Server' : 'Start Server'}
            </button>
            <button 
              className="btn btn-sm btn-ghost"
              onClick={refreshModels}
              disabled={!isServerRunning || isLoading}
            >
              Refresh
            </button>
          </div>

          {/* Error Display */}
          {error && (
            <div className="alert alert-error mb-4">
              <span>{error}</span>
            </div>
          )}

          {/* Create Model Form */}
          <form onSubmit={handleCreateModel} className="form-control gap-4 mb-4">
            <div className="flex gap-4">
              <input
                type="text"
                placeholder="Model Name"
                className="input input-bordered flex-1"
                value={modelName}
                onChange={(e) => setModelName(e.target.value)}
                disabled={!isServerRunning || isLoading}
              />
              <input
                type="text"
                placeholder="Model File"
                className="input input-bordered flex-1"
                value={modelFile}
                onChange={(e) => setModelFile(e.target.value)}
                disabled={!isServerRunning || isLoading}
              />
              <button 
                type="submit" 
                className="btn btn-primary"
                disabled={!isServerRunning || isLoading || !modelName || !modelFile}
              >
                Create Model
              </button>
            </div>
          </form>

          {/* Models List */}
          <div className="overflow-x-auto">
            <table className="table w-full">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Size</th>
                  <th>Modified</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {models.map((model) => (
                  <tr key={model.name}>
                    <td>{model.name}</td>
                    <td>{model.size}</td>
                    <td>{model.modified}</td>
                    <td>
                      <button
                        className="btn btn-sm btn-error"
                        onClick={() => deleteModel(model.name)}
                        disabled={isLoading}
                      >
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
                {models.length === 0 && (
                  <tr>
                    <td colSpan={4} className="text-center">
                      {isServerRunning ? 'No models available' : 'Start the server to view models'}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Loading Indicator */}
          {isLoading && (
            <div className="flex justify-center mt-4">
              <div className="loading loading-spinner loading-lg text-primary"></div>
            </div>
          )}
        </div>
      </div>
    </IonContent>
  );
}; 